package com.macbulldev.poc.testgin.controller;

import java.util.Date;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.log4j.Logger;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.macbulldev.poc.testgin.domain.AppRole;
import com.macbulldev.poc.testgin.domain.AppUser;
import com.macbulldev.poc.testgin.domain.EventLog;
import com.macbulldev.poc.testgin.domain.Rate;
import com.macbulldev.poc.testgin.domain.Scenario;
import com.macbulldev.poc.testgin.domain.StateOrProvince;
import com.macbulldev.poc.testgin.service.WebappUtils;


@org.springframework.roo.addon.web.mvc.controller.RooWebScaffold(path = "stateorprovince", automaticallyMaintainView = false, formBackingObject = com.macbulldev.poc.testgin.domain.StateOrProvince.class)
@org.springframework.web.bind.annotation.RequestMapping("/stateorprovince/**")
@org.springframework.stereotype.Controller
public class StateOrProvinceController {
	
	
	@RequestMapping(value = "/stateorprovince/list", method = RequestMethod.GET)    
    public String renderStateOrProvinceList(@RequestParam(value = "pageNumber", required = false) Integer page, ModelMap modelMap) {    

		
		int sizeNo = 20;           
        int pageNumber= page == null ? 0 : page;
        
        modelMap.addAttribute("stateorprovinces",StateOrProvince.findStateOrProvinceEntries(pageNumber*sizeNo, sizeNo));            
        Long count = StateOrProvince.countStateOrProvinces();
        modelMap.addAttribute("maxPageNumber", (Long)(count/sizeNo));
        return "stateorprovince/list";        
    }
	
	@RequestMapping(value = "/stateorprovince/create", method = RequestMethod.GET)    
    public String createStateOrProvince(ModelMap modelMap) {    
        modelMap.addAttribute("stateOrProvince", new StateOrProvince());        
        modelMap.addAttribute("stateOrProvinces", StateOrProvince.findAllStateOrProvinces());        
        return "stateorprovince/create";        
    }
    
   
	
	

	@RequestMapping(value = "/stateorprovince", method = RequestMethod.POST)    
    public String create(@Valid StateOrProvince stateOrProvince, BindingResult result, ModelMap modelMap, HttpSession session) {    
        if (stateOrProvince == null) throw new IllegalArgumentException("A stateOrProvince is required");        
        
        StateOrProvince sop = new StateOrProvince();
        
        
        if(!result.hasErrors())
        {
        	
        	sop = sop.getByDisplayName(stateOrProvince.getDisplayName());
        	
        	
        	if(sop != null)
        	{
        		result.addError(new FieldError("stateOrProvince","displayName","Error: A State Already Exists with This Name."));
        	}
        	
        	sop = sop.getByCode(stateOrProvince.getCode());
        
        
        	if(sop != null)
        	{
        		result.addError(new FieldError("stateOrProvince","code","Error: A State Already Exists with This Code."));
        	}
        	
        }
        
        if (result.hasErrors()) {        
            modelMap.addAttribute("stateOrProvince", stateOrProvince);            
            modelMap.addAttribute("rates", Rate.findAllRates());            
            modelMap.addAttribute("scenarios", Scenario.findAllScenarios());            
            return "stateorprovince/create";            
        }
        
        AppUser sessionUser = WebappUtils.getAuthenticationObject(session);
        
        stateOrProvince.setCreateUsername(sessionUser.getName());
        stateOrProvince.setUpdateUsername(sessionUser.getName());
        
        stateOrProvince.setCreateTs(new Date());
        stateOrProvince.setUpdateTs(new Date());
        
        EventLog log = new EventLog();
    	log.setCreateTs(new Date());
    	log.setCreateUsername(sessionUser.getName());

    	log.setObjectClass(StateOrProvince.class.getSimpleName());
    	log.setOperation("State "+stateOrProvince.getDisplayName()+" created");
    	log.persist();
        
        
        stateOrProvince.persist();        
        return "redirect:/stateorprovince/" + stateOrProvince.getId();        
    }

	@RequestMapping(value = "/stateorprovince/form", method = RequestMethod.GET)    
    public String createForm(ModelMap modelMap) {    
        modelMap.addAttribute("stateOrProvince", new StateOrProvince());        
        modelMap.addAttribute("rates", Rate.findAllRates());        
        modelMap.addAttribute("scenarios", Scenario.findAllScenarios());        
        return "stateorprovince/create";        
    }

	@RequestMapping(value = "/stateorprovince/{id}", method = RequestMethod.GET)    
    public String show(@PathVariable("id") Long id, ModelMap modelMap) {    
        if (id == null) throw new IllegalArgumentException("An Identifier is required");        
        modelMap.addAttribute("stateOrProvince", StateOrProvince.findStateOrProvince(id));        
        return "stateorprovince/show";        
    }

	@RequestMapping(value = "/stateorprovince", method = RequestMethod.GET)    
    public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, ModelMap modelMap) {    
        if (page != null || size != null) {        
            int sizeNo = size == null ? 10 : size.intValue();            
            modelMap.addAttribute("stateorprovinces", StateOrProvince.findStateOrProvinceEntries(page == null ? 0 : (page.intValue() - 1) * sizeNo, sizeNo));            
            float nrOfPages = (float) StateOrProvince.countStateOrProvinces() / sizeNo;            
            modelMap.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));            
        } else {        
            modelMap.addAttribute("stateorprovinces", StateOrProvince.findAllStateOrProvinces());            
        }        
        return "stateorprovince/list";        
    }

	@RequestMapping(method = RequestMethod.PUT)    
    public String update(@Valid StateOrProvince stateOrProvince, BindingResult result, ModelMap modelMap, HttpSession session) {    
        if (stateOrProvince == null) throw new IllegalArgumentException("A stateOrProvince is required");        
        
        StateOrProvince sop = new StateOrProvince();
        StateOrProvince current = sop.findStateOrProvince(stateOrProvince.getId());
        
        if(!result.hasErrors())
        {
        	
        	if(!stateOrProvince.getDisplayName().equalsIgnoreCase(current.getDisplayName()))
        	{
        	
        		sop = sop.getByDisplayName(stateOrProvince.getDisplayName());
        	
        	
        		if(sop != null)
        		{
        			result.addError(new FieldError("stateOrProvince","displayName","Error: A State Already Exists with This Name."));
        		}
        		
        	}
        	
        	if(!stateOrProvince.getCode().equalsIgnoreCase(current.getCode()))
        	{
        	
        		sop = sop.getByCode(stateOrProvince.getCode());
        
        
        		if(sop != null)
        		{
        			result.addError(new FieldError("stateOrProvince","code","Error: A State Already Exists with This Code."));
        		}
        	}
        	
        }
        
        if (result.hasErrors()) {        
            modelMap.addAttribute("stateOrProvince", stateOrProvince);            
            modelMap.addAttribute("rates", Rate.findAllRates());            
            modelMap.addAttribute("scenarios", Scenario.findAllScenarios());            
            return "stateorprovince/update";            
        }
        
        sop = sop.findStateOrProvince(stateOrProvince.getId());
        
        stateOrProvince.setCreateUsername(sop.getCreateUsername());
        stateOrProvince.setCreateTs(sop.getCreateTs());
        
        AppUser sessionUser = WebappUtils.getAuthenticationObject(session);
        stateOrProvince.setUpdateUsername(sessionUser.getName());
        stateOrProvince.setUpdateTs(new Date());
        
        EventLog log = new EventLog();
    	log.setCreateTs(new Date());
    	log.setCreateUsername(sessionUser.getName());

    	log.setObjectClass(StateOrProvince.class.getSimpleName());
    	log.setOperation("State "+stateOrProvince.getDisplayName()+" Updated");
    	log.persist();
        
        
        stateOrProvince.merge();        
        return "redirect:/stateorprovince/" + stateOrProvince.getId();        
    }

	@RequestMapping(value = "/stateorprovince/{id}/form", method = RequestMethod.GET)    
    public String updateForm(@PathVariable("id") Long id, ModelMap modelMap) {    
        if (id == null) throw new IllegalArgumentException("An Identifier is required");        
        modelMap.addAttribute("stateOrProvince", StateOrProvince.findStateOrProvince(id));        
        modelMap.addAttribute("rates", Rate.findAllRates());        
        modelMap.addAttribute("scenarios", Scenario.findAllScenarios());        
        return "stateorprovince/update";        
    }

	@RequestMapping(value = "/stateorprovince/{id}", method = RequestMethod.DELETE)    
    public String delete(@PathVariable("id") Long id, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size,HttpSession session) {    
        if (id == null) throw new IllegalArgumentException("An Identifier is required");        
        
        AppUser sessionUser = WebappUtils.getAuthenticationObject(session);
        
        EventLog log = new EventLog();
    	log.setCreateTs(new Date());
    	log.setCreateUsername(sessionUser.getName());

    	log.setObjectClass(StateOrProvince.class.getSimpleName());
    	log.setOperation("State "+ StateOrProvince.findStateOrProvince(id).getDisplayName()+" Deleted");
    	log.persist();
        
        StateOrProvince.findStateOrProvince(id).remove();        
        
        return "redirect:/stateorprovince?page=" + ((page == null) ? "1" : page.toString()) + "&size=" + ((size == null) ? "10" : size.toString());        
    }
}
